DROP PROCEDURE [dbo].[pr3200]
GO

CREATE PROCEDURE [dbo].[pr3200] @DivisionID varchar(20), @TranMonth as int, @TranYear as int,
				@BeginDate as datetime,
				@EndDate as datetime

	
 AS

Declare @Closing As Bit,
	@NextMonth 	TinyInt,
	@NextYear 	Smallint,
	@PeriodNum 	TinyInt,
	@MaxPeriod	Int 
	
	
	Select 	@PeriodNum = PeriodNum
	From	tb0001
	If @PeriodNum Is Null 
		Set @PeriodNum = 12

	Set @NextMonth = @TranMonth % @PeriodNum + 1
	Set @NextYear = @TranYear + @TranMonth/@PeriodNum

	Select  	@Closing = Closing
	From 	tb3060
	Where 	DivisionID = @DivisionID And TranMonth = @TranMonth And TranYear = @TranYear
		
	Select 	@MaxPeriod = Max(TranMonth + TranYear * 100)
 	From	tb3060
	Where	DivisionID = @DivisionID

	If  @Closing <> 1 
	Begin	
		Update tb3060
		Set 	Closing = 1
		From 	tb3060
		Where 	DivisionID = @DivisionID And TranMonth =@TranMonth And TranYear = @TranYear

		IF	@MaxPeriod < (@NextMonth + @NextYear * 100)
		Begin
			Insert    	tb3060  (TranMonth,TranYear, DivisionID,Closing, BeginDate, EndDate) 
			Values(@NextMonth,@NextYear, @DivisionID,0,@BeginDate,@EndDate)
			If Exists (Select 1 From tb0000 Where DefDivisionID = @DivisionID)
			Begin
				Update tb3000
				Set 	TranMonth = @NextMonth,
					TranYear = @NextYear			
			End
		End	
		else
		Begin	
			Update 	tb3060
			Set 	BeginDate = @BeginDate,
				EndDate = @EndDate
			From 	tb3060
			Where 	DivisionID = @DivisionID And TranMonth = @NextMonth And TranYear = @NextYear
		end


	End


GO